package com.taocore.top.title.service;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.NamingException;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.DefaultHttpClient;

import com.taocore.top.title.db.DBUtils;
import com.taocore.top.title.db.Dao;

public class RealTimeKeywordsImport {

	static Logger _log = Logger.getLogger(RealTimeKeywordsImport.class.getName());
	
	public static final String[] CATEGORIES = {
		"16", "50006843", "30", "50011740", "1625", "50006842", "TR_NRDBPS", "TR_GMDXPS", "TR_ZB",
		"TR_DNJXGPJ", "TR_SJ", "TR_SYQC", "TR_YYCP", "TR_CFJD", "TR_SHJD", "TR_BG", "50008090",
		"TR_MRHF", "TR_CZ",
		"TR_BBYP", "TR_BBSP", "TR_BBFS", "TR_BBWJ", "TR_YFSY", "TR_YFFSSY",
		"TR_LS", "TR_MSSP", "TR_CYKFCYP", "50012472",
		"TR_HW", "TR_YD", "TR_SJZZBZ", "23", "50011949", "50017300",
		"TR_RYLP", "TR_CPBY", "TR_CFCYYJ", "TR_RHQJ", "2813", "50008075", "50020611", "50020808", "50020670", "27", "50008164", "50020485", "50023575",
		"TR_SCAH", "TR_YX", "TR_MTCZXCJQCXGPJ", "TR_QXPJ", "TR_CW", "TR_XH"};
	
	public static final int PAGES = 3;

	public static void importData() throws IOException, URISyntaxException
	{
		Connection conn = null;
		try
		{
			conn = DBUtils.getConnection();
			Dao.INSTANCE.clearRealTimeKeywords(conn);
			_log.info("table cleared.");
			importPages(null, PAGES, conn);
			for (String cat : CATEGORIES)
			{
				importPages(cat, PAGES, conn);
			}
		} catch (NamingException e) {
			_log.log(Level.SEVERE, "", e);
		} catch (SQLException e) {
			_log.log(Level.SEVERE, "", e);
		}
		finally
		{
			DBUtils.close(conn, null, null);
		}
	}
	
	private static void importPages(String cat, int pages, Connection conn) throws IOException, URISyntaxException
	{
		for (int i = 1; i <= pages; i++)
		{
			importData(cat, i, conn);
		}
	}
	
	private static void importData(String category, int pageNo, Connection conn) throws IOException, URISyntaxException
	{
		_log.info("category: " + category);
		HttpClient httpclient = new DefaultHttpClient();
		URIBuilder builder = new URIBuilder();
		builder.setScheme("http").setHost("taoke.alimama.com").setPath("/spreader/searchKeywordsFromTop.do")
		    .setParameter("type", "query")
		    .setParameter("up", "false")
		    .setParameter("p", String.valueOf(pageNo));
		if (category != null)
		{
			builder.setParameter("cat", category);
		}
		URI uri = builder.build();
		_log.info("uri: " + uri);
		HttpPost post = new HttpPost(uri);
		HttpResponse response = httpclient.execute(post);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
		    InputStream in = entity.getContent();
		    try {
		        String json = IOUtils.toString(in);//, "UTF-8");
		        JSONObject jsonObject = JSONObject.fromObject(json);
		        JSONArray array = jsonObject.getJSONArray("datas");
		        _log.info("array.size: " + array.size());
		        PreparedStatement statement = null;
				try
				{
					String sql = "insert into day_keywords_t(cat_c, keyword_c, idx_c, idx_chg_rate_c) values(?,?,?,?)";
	    			statement = conn.prepareStatement(sql);
			        for (int i = 0, n = array.size(); i < n; i++)
			        {
			        	JSONObject keywordObject =  array.getJSONObject(i);
			        	String keyword = keywordObject.getString("objectName");
			        	long idx = keywordObject.getLong("idx");
			        	double idxChgRate = keywordObject.getDouble("idxChgRate");
			        	
			        	statement.setString(1, category);
		    			statement.setString(2, keyword);
		    			statement.setLong(3, idx);
		    			statement.setFloat(4, (float) idxChgRate);
		    			statement.addBatch();
			        }
			        statement.executeBatch();
				}
				catch (SQLException e) {
					_log.log(Level.SEVERE, "", e);
				} 
				finally
				{
					DBUtils.close(null, statement, null);
				}
		    }
		    catch (JSONException e)
		    {
		    	_log.log(Level.SEVERE, "", e);
		    }
		    catch (Exception e)
		    {
		    	_log.log(Level.SEVERE, "", e);
		    }
		    finally {
		        in.close();
		    }
		}
	}
}
